//
//  DelayItem.swift
//  DSP
//
//  Created by tucici on 2024/5/16.
//

import UIKit
import TCCKit
class DelayItem: UICollectionViewCell {
    private var title : UILabel!
    private var input : UITextField!
    private var btn : UIButton!
    private var line : UIView!
    private var bg : UIView!
    var block : ((ChannelModel)->Void)?
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
        NotifyTool.add(self, #selector(updateDelayAction), updateDelay)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        title = UILabel()
        title.font = font(12)
        title.textAlignment = .center
        title.textHexColor = HEX_BLACK
        title.borderHexColor = HEX_BLACK
        title.cornerRadius = 4.k_h
        title.borderWidth = 1
        
        bg = UIView()
        bg.borderHexColor = HEX_BLACK
        bg.cornerRadius = 4.k_h
        bg.borderWidth = 1
        
        input = UITextField()
        input.delegate = self
        input.textAlignment = .center
        input.textHexColor = HEX_BLACK
        input.keyboardType = .decimalPad
        input.font = font(10,.light)
        input.minimumFontSize = 8
        input.adjustsFontSizeToFitWidth = true
        
        line = UIView()
        line.bgHexColor = HEX_BLACK
        
        btn = UIButton(type: .custom)
        btn.setTitle("ms", for: .normal)
        btn.textHexColor = HEX_BLACK
        btn.titleLabel?.font = font(10,.light)
        btn.addTarget(self, action: #selector(actionForBtn), for: .touchUpInside)
        
        contentView.addSubview(title)
        contentView.addSubview(bg)
        bg.addSubview(input)
        bg.addSubview(line)
        bg.addSubview(btn)
        
        title.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(k_h(20))
        }
        
        bg.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(title.snp.bottom).offset(k_h(5))
            make.height.equalTo(k_h(16))
        }
        
        input.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.right.equalTo(line.snp.left)
        }
        
        line.snp.makeConstraints { make in
            make.top.bottom.centerX.equalToSuperview()
            make.width.equalTo(1)
        }
        
        btn.snp.makeConstraints { make in
            make.top.bottom.right.equalToSuperview()
            make.left.equalTo(line.snp.right)
        }
    }
    
    func updateUI(){
        title.text = model.name
        if model.delayType == 1{
            btn.setTitle("ms", for: .normal)
            input.text = String(format: "%0.1f", model.delay)
        }else if model.delayType == 2 {
            btn.setTitle("cm", for: .normal)
            input.text = String(format: "%d", Int((model.delay * 34.3).rounded?(0) ?? 0) )
        } else if model.delayType == 3 {
            btn.setTitle("in", for: .normal)
            input.text = String(format: "%d", Int((model.delay * 34.3 * 0.3937).rounded?(0) ?? 0) )
        }
        
        title.bgHexColor = model.select && model.enable ? HEX_RED : HEX_BG
        title.borderHexColor = !model.enable ? HEX_BORDER_DISABLE : (model.select ? HEX_RED : HEX_BLACK)
        title.textHexColor = !model.enable ? HEX_TEXT_DISABLE : HEX_BLACK
        title.font = font(12, model.select ? .bold : .regular)
        
        input.isUserInteractionEnabled = model.enable && model.select
        btn.isUserInteractionEnabled = model.enable && model.select
        
        input.textHexColor = model.enable && model.select ? HEX_BLACK : HEX_TEXT_DISABLE
        
        btn.textHexColor = model.enable && model.select ? HEX_BLACK : HEX_TEXT_DISABLE
        
        bg.borderHexColor = model.enable && model.select ? HEX_RED : HEX_BORDER_DISABLE
        line.bgHexColor = model.enable && model.select ? HEX_RED : HEX_BORDER_DISABLE
    }
    @objc func actionForBtn(){
        if model.delayType == 1{model.delayType = 2}
        else if model.delayType == 2{model.delayType = 3}
        else if model.delayType == 3{model.delayType = 1}
        updateUI()
    }
    
    var model = ChannelModel(){
        didSet{
            updateUI()
        }
    }
    
    @objc func updateDelayAction(notify:Notification){
        guard let ch = notify.object as? ChannelModel, model.num == ch.num else{return}
        model = ch
    }
}

//MARK: - UITextFieldDelegate
extension DelayItem:UITextFieldDelegate{
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = ""
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        updateUI()
    }
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.markedTextRange != nil || textField.text == ""{return}
        if model.delayType == 1{
            let value = Float(textField.text?.floatValut() ?? 0)
            model.delay = min(value, 8.0)
        }else if model.delayType == 2 {
            var value = Float(textField.text?.floatValut() ?? 0)
            value = Float((value / 34.3).rounded?(1) ?? 0.0)
            model.delay = min(value, 8.0)
        } else if model.delayType == 3 {
            var value = Float(textField.text?.floatValut() ?? 0)
            value = Float((value / 34.3 / 0.3937).rounded?(1) ?? 0.0)
            model.delay = min(value, 8.0)
        }
        block?(model)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text ?? ""
        if string == "" {return true}
        if (text + string).floatValut() > 999 {return false}
        if text.contains(".") && string.contains(".") {return false}
        if (text + string).count > 3 {return false}
        if string != "." && !string.isNumber()  {return false}
        return true
    }
}
